/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.Constants;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.Soundbank;
import javax.swing.JOptionPane;

/**
 *
 * @author Long
 */
public class SampleTranfer {

    
    private Socket socket;
    private BufferedReader bufferedReader;
    private DataOutputStream dataOutputStream;

    public SampleTranfer(String host, int port, int type) {
        if (type == Constants.HOST) {
            initServer(port);
        } else if (type == Constants.CLIENT) {
            initClient(host, port);
        }
    }

    private void initServer(int port) {
        try {
            ServerSocket server = new ServerSocket(port);
            socket = server.accept();
            server.close();
            createBuffer();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void initClient(String host, int port) {
        try {
            socket = new Socket(host, port);
            createBuffer();
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void createBuffer() {
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public void sendData(String data) {
        try {
            for (int i = 0; i < data.length(); i++) {
                dataOutputStream.write((byte) data.charAt(i));
            }
            dataOutputStream.write(13);
            dataOutputStream.flush();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Ngắt kết nối");
            System.exit(0);
            ex.printStackTrace();
        }
    }

    public String receiveData() {
        String data = "";
        try {
            data = bufferedReader.readLine();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Ngắt kết nối");
            System.exit(0);
            ex.printStackTrace();
        }
        return data;
    }

    public void closeConnection() {
        try {
            socket.close();
            bufferedReader.close();
            dataOutputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
